<?php
/**
 * 活动订单.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;


use think\Db;

class Order extends ApiCommon
{
    protected $orderTable = 'lite_order';
    protected $goodsOrderTable = 'store_order';
    protected $goodsOrderListTable = 'store_order_list';
    protected $activityTable = 'lite_activity';
    protected $groupTable = 'lite_activity_group';
    protected $packageTable = 'lite_activity_package';
    protected $couponsTable = 'lite_coupons';
    protected $recordTable = 'lite_coupons_record';
    protected $memberTable = 'store_member';


    public function __construct()
    {
        parent::__construct();
    }

    public function confirm()
    {
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        $id = $this->request->param('product_id');
//        $id = 5;
        $activity = new Activity();
        $detail = $activity->__detail($id, true);
        $this->success('', $detail);
    }

    public function createOrder()
    {
        $data = $this->request->param();
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        $totalPrice = 0;
        if(isset($data['group_id'])){
            $totalPrice += db($this->groupTable)->where(['id' => $data['group_id']])->value('price');
        }
        if(isset($data['package_id'])){
            $totalPrice += db($this->packageTable)->where(['id' => $data['package_id']])->value('price');
        }
        if(isset($data['goods_info']) && !empty($data['goods_info'])){
//            var_dump($data['goods_info']);exit;
            foreach ($data['goods_info'] as $key => $item){
                foreach ($item as $productId => $attr){
                    $productIds[$productId] = $attr;
                    $totalPrice += db('store_goods_list')->where(['goods_id' => $productId, 'goods_spec' => $attr])->value('price_selling');
                }
            }
        }
        if($totalPrice != $data['total_price']){
            $this->error('价格错误！');
        }

        $insertData = [
            'user_id' => $this->openid,
            'price' => $totalPrice,
            'activity_id' => $data['activity_id'],
            'group_id' => $data['group_id'],
            'package_id' => isset($data['package_id']) ? $data['package_id']:0,
            'status' => 2, //订单状态(0已取消1预订单待补全2新订单待支付3已支付待审核4审核通过5审核未通过)
            'pay_status' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'count' => 1,
            'order_sn' => $this->createOrderSn($data['activity_id'], $data['group_id']),
            'remark' => $data['remark'],
            'member_address_id' => $data['member_address_id']
//            'form_id' => $data['form_id']
        ];
        if(isset($productIds)){
            $insertData['product_id'] = json_encode($productIds);
        }
        // 启动事务
        Db::startTrans();
        try {
            //字段+1
//            Db::table($this->activityTable)->setInc('has_count');
            $orderId = Db::table($this->orderTable)->insertGetId($insertData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $this->success('订单创建成功！', $orderId);
    }

    private function createOrderSn($id = 0, $group_id = 0){
        return  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$id.$group_id;
    }

    //获取订单信息
    public function getOrder()
    {
        $data = $this->request->param();
        $res = db($this->orderTable)->where(['id' => $data['orderId']])->find();
        //产品名
        $res['productName'] = db($this->activityTable)->where(['id' => $res['activity_id']])->value('name');
        $res['cate_id'] = db('lite_activity_cate')->where(['activity_id' => $res['activity_id']])->column('id,cate_id', 'id');
        $res['country'] = db($this->activityTable)->where(['id' => $res['activity_id']])->value('country');
        $res['groupName'] = db($this->groupTable)->where(['id' => $res['group_id']])->value('name');
        if(!empty($res['package_id']) && $res['package_id'] > 0){
            $res['packageName'] = db($this->packageTable)->where(['id' => $res['package_id']])->value('name');
        }
        if(!empty($res['product_id'])){
            $productData = [];
            $product = json_decode($res['product_id'], true);
            foreach ($product as $productId => $attr){
                $productData[$productId]['attr'] = $attr;
                $productData[$productId]['name'] = db('store_goods')->where(['id' => $productId])->value('title');
            }
            $res['productData'] = $productData;
        }
        //查询优惠券
        $now = date('Y-m-d H:i:s');
        $where[] = ['is_deleted' , '=', 0];
        $where[] = ['open_id' , '=', $this->openid];
        $where[] = ['status' , '=',  1];
        $where[] = ['use_type' , '=',  1]; // 活动
        $where2[] = ['use_end_time' , '>',  $now];
        $where2[] = ['use_start_time' , '<',  $now];
        $where3[] = ['limit_use_type' , '=',  3];
        $couponsList1 = db::table($this->recordTable)->where($where)->where($where2)->select();
        $couponsList2 = db::table($this->recordTable)->where($where)->where($where3)->select();
        $couponsList = array_merge($couponsList1, $couponsList2);
        $couponsIds = array_column($couponsList, 'coupons_id');
        $couponsData = db::table($this->couponsTable)->where('id', 'in', $couponsIds)->column('id, name, use_type, discount_value, activity_type, discount,meet_value,reduction,amount','id');
        foreach ($couponsList as $key => $value){
            //限制单个商品
            if(!in_array($res['activity_id'], explode(',', $value['product_id'])) && $value['product_id'] != -1){
                unset($couponsList[$key]);continue;
            }

            //计算折扣金额
            $coupons = $couponsData[$value['coupons_id']]; //折扣方式

            //限制活动类型(是)
            if($coupons['use_type'] == 1 && $coupons['activity_type'] == 1 && !in_array(8, $res['cate_id'])){  //活动类型（1签证，2海外3国内）
                unset($couponsList[$key]);continue;
            }

            //限制活动类型
            if($coupons['use_type'] == 1 && $coupons['activity_type'] == 2 && ($res['country'] == '中国' || in_array(8, $res['cate_id']))){  //活动类型（1签证，2海外3国内）
                unset($couponsList[$key]);continue;
            }

            //限制活动类型
            if($coupons['use_type'] == 1 && $coupons['activity_type'] == 3 && ($res['country'] != '中国' || in_array(8, $res['cate_id'])) ){  //活动类型（1签证，2海外3国内）
                unset($couponsList[$key]);continue;
            }


            if($value['coupons_type'] == 1 && ($coupons['discount_value'] == -1 || $res['price'] >= $coupons['discount_value'])){ //优惠券1折扣券，2满x减n,3无条件立减
                $couponsList[$key]['reduced_price'] = $res['price'] * (1-$coupons['discount']/100);
            }else if($value['coupons_type'] == 2 && ($coupons['meet_value'] == -1 || $res['price'] >= $coupons['meet_value'])){
                $couponsList[$key]['reduced_price'] = $coupons['reduction'];
            }else if($value['coupons_type'] == 3){
                $couponsList[$key]['reduced_price'] = $coupons['amount'];
            }else{
                unset($couponsList[$key]);continue;
            }

            if(isset($couponsList[$key])){
                $couponsList[$key]['name'] = $coupons['name'];
                isset($couponsList[$key]) ? $couponsList[$key]['reduced_price'] = number_format($couponsList[$key]['reduced_price'], 2, '.', ''): null;
                if($couponsList[$key]['reduced_price'] > $res['price']){
                    $couponsList[$key]['reduced_price'] = number_format($res['price'], 2, '.', '');
                }
            }
        }
        if(count($couponsList) > 0){
            $res['couponsList'] = $couponsList;
        }else{
            $res['couponsList'] = [];
        }

        //余额
        $amount = db($this->memberTable)->where(['openid' => $this->openid])->field('amount, use_amount')->find();
        $res['amount'] = number_format($amount['amount'] - $amount['use_amount'], 2, '.', '');

        $this->success('订单信息获取成功！', $res);
    }

    public function doPay()
    {
        $orderId = $this->request->param('order_id');
        if(empty($orderId)){
            $this->error('请传入订单ID！');
        }
        $orderInfo = db($this->orderTable)->find($orderId);


        $payType = $this->request->param('pay_type');
        $wxPay = new WxPay();
        if( $payType == 1){
            $orderInfo['product_name'] = db($this->activityTable)->where(['id' => $orderInfo['activity_id']])->value('name');
            $orderInfo['group_name'] = db($this->groupTable)->where(['id' => $orderInfo['group_id']])->value('name');
            $orderInfo['body'] = '活动:' . $orderInfo['product_name']. ';组别：'.$orderInfo['group_name'];
            //优惠券
            $couponsRecordId = $this->request->param('couponsRecordId');
            if(!empty($couponsRecordId)){
                $couponsRecordData = db::table($this->recordTable)->where(['id' => $couponsRecordId]) ->find();
                $coupons = db::table($this->couponsTable)->where(['id' => $couponsRecordData['coupons_id']]) ->find();

                if($couponsRecordData['coupons_type'] == 1 && ($coupons['discount_value'] == -1 || $orderInfo['price'] >= $coupons['discount_value'])){ //优惠券1折扣券，2满x减n,3无条件立减
                    $reducedPrice = $orderInfo['price'] * (1-$coupons['discount']/100);

                }else if($couponsRecordData['coupons_type'] == 2 && ($coupons['meet_value'] == -1 || $orderInfo['price'] >= $coupons['meet_value'])){
                    $reducedPrice = $coupons['reduction'];
                }else if($couponsRecordData['coupons_type'] == 3){
                    $reducedPrice = $coupons['amount'];
                }else{
                    $reducedPrice = 0;
                }
                if($reducedPrice > $orderInfo['price']){
                    $reducedPrice = number_format($orderInfo['price'], 2, '.', '');
                }

                //更新优惠券和金额
                if(empty($orderInfo['envelope_id'])){
                    $upData = [
                        'envelope_id' => $couponsRecordId,
                        'reduced_price' => $reducedPrice,
                    ];
                    $updateCouponsResult =db($this->orderTable)->where(['id' => $orderId])->update($upData);
                    if(!$updateCouponsResult){
                        $this->error('优惠券设置错误！', $updateCouponsResult);
                    }
                }else if(!empty($orderInfo['envelope_id']) && $orderInfo['envelope_id'] != $couponsRecordId){
                    //防止订单重复，重新生成订单号
                    $upData = [
                        'envelope_id' => $couponsRecordId,
                        'reduced_price' => $reducedPrice,
                        'order_sn' =>$this->createOrderSn($orderInfo['activity_id'], $orderInfo['group_id'])
                    ];
                    $updateCouponsResult = db($this->orderTable)->where(['id' => $orderId])->update($upData);
                    if(!$updateCouponsResult){
                        $this->error('优惠券设置错误！2', $updateCouponsResult);
                    }else{
                        $orderInfo['order_sn'] = $upData['order_sn'];
                    }
                }
                $reducedPrice = number_format($reducedPrice, 2, '.', '');
                if($reducedPrice == $this->request->param('reduced_price')){
                    $orderInfo['envelope_id'] = $couponsRecordId;
                    $orderInfo['reduced_price'] = $reducedPrice;
                }else{
                    $this->error('优惠券金额错误！', $reducedPrice);
                }
                //重新计算金额
                $orderInfo['price'] = number_format($orderInfo['price']-$reducedPrice, 2, '.', '');
            }
            if($orderInfo['price'] == 0){ // 无需支付的情况
                $res = $wxPay->update($orderInfo['order_sn'], $orderInfo['order_sn'], 0);
                if($res){
                    $this->success('订单支付成功！', [], 19);
                }
            }
        }else if($payType == 3){
            if(!empty($couponsRecordId)) {
                $this->error('储值不支持优惠券使用！');
            }
            $member = db($this->memberTable)->where(['openid' => $this->openid])->field('amount,use_amount')->find();
            $amount = $member['amount'] - $member['use_amount'];
            if($amount < $orderInfo['price']){
                $this->error('账户余额不足！', [], 0);
            }
            $res = $wxPay->update($orderInfo['order_sn'], $orderInfo['order_sn'], $orderInfo['price'], 3);
            if($res){
                $this->success('订单支付成功！', [], 29);
            }else{
                $this->error('订单支付失败！', [], 0);
            }
        }else{
            $this->error('支付方式错误！');
        }


        $data = $wxPay->unifiedOrder($orderInfo);
        $this->success('创建预订单成功！', $data);
    }

//    /**
//     * 订单状态更新
//     * @param string $order_no 订单号
//     * @param string $pay_no 交易号
//     * @param string $pay_price 交易金额
//     * @param string $type 支付类型
//     * @return boolean
//     * @throws \think\Exception
//     * @throws \think\exception\PDOException
//     */
//    private function update($order_no, $pay_no, $pay_price, $type = 'wechat')
//    {
//        $where = ['order_sn' => $order_no, 'pay_status' => '0', 'status' => '2'];
//        // 检查订单支付状态
//        $order = db('lite_order')->where($where)->find();
//        if (empty($order)) return false;
//        // 更新订单支付状态
//        $result = db('lite_order')->where($where)->update([
//            'pay_type'  => $type, 'pay_no' => $pay_no, 'status' => '3',
//            'pay_price' => $pay_price, 'pay_status' => '1', 'pay_at' => date('Y-m-d H:i:s'),
//        ]);
//        // 调用会员升级机制
////        Order::update($order['order_no']);
//        //更新优惠券使用状态
//        db($this->recordTable)->where(['id' => $order['envelope_id']])->update(['status' => 2, 'used_time' => date('Y-m-d H:i:s')]);
//        return $result !== false;
//    }


    public function checkPay()
    {
        $orderId = $this->request->param('id');
        if(empty($orderId)){
            $this->error('请传入订单ID！');
        }
        $orderInfo = db($this->orderTable)->find($orderId);
        //'pay_no' => $pay_no, 'status' => '1','pay_price' => $pay_price, 'pay_status' => '1',
        if($orderInfo['pay_status'] == 1 && $orderInfo['status'] == 3 && !empty($orderInfo['status'])){
            $res['paySuccess'] = true;
            $this->success('支付成功！', $res);
        }
        $res['paySuccess'] = false;
        $this->error('支付失败！', $res);
    }

    public function order_list()
    {
        $data = $this->request->param();
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        $where = ['user_id' => $this->openid, 'order_type' => 0];
        if(isset($data['status']) && $data['status'] != 0){
            $where['status'] = $data['status'];
        }
        //总数量
        $totalSize = db($this->orderTable)->where($where)->count();
        //当前页码
        $current_page = $this->request->param('pageNum', 1);
        //分页大小
        $size = $this->request->param('size', 3);



        $list = db($this->orderTable)->where($where)->limit(($current_page - 1) * $size, $size)->order('id desc')->select();

        $activityList = db($this->activityTable)->field('id,name,pic,start_time')->whereIn('id', array_unique(array_column($list, 'activity_id')))->select();
        $groupList = db($this->groupTable)->field('id,name,price')->whereIn('id', array_unique(array_column($list, 'group_id')))->select();
        $packageList = db($this->packageTable)->field('id,name,price')->whereIn('id', array_unique(array_column($list, 'package_id')))->select();

        $res = [];
        foreach ($list as $key => $value){
            $res[$key]['id'] = $value['id'];
            $res[$key]['time'] = $value['create_time'];
            $res[$key]['state'] = $value['status'];
            $res[$key]['price'] = $value['price'];
            $res[$key]['pay_price'] = $value['pay_price'];
            $res[$key]['order_sn'] = $value['order_sn'];

            foreach ($activityList as $activity) if ($activity['id'] === $value['activity_id']) {
                $res[$key]['activityInfo'] = $activity;
                $res[$key]['image'] = $activity['pic'];
                $res[$key]['title'] = $activity['name'];
                $res[$key]['start_time'] = $activity['start_time'];
            }
            foreach ($groupList as $group) if ($group['id'] === $value['group_id']) {
                $res[$key]['groupInfo'] = $group;
            }
            foreach ($packageList as $package) if ($package['id'] === $value['package_id']) {
                $res[$key]['packageInfo'] = $package;
            }
        }
        $resData['list'] = $res;
//        $resData['page']['totalSize'] = $totalSize;
        $resData['page']['pageSize'] = ceil($totalSize / $size);
        $this->success('订单获取成功！', $resData);
    }

    public function goods_order_list()
    {
        $data = $this->request->param();
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        $where = ['mid' => $this->openid];
        if(isset($data['status']) && $data['status'] != 0){
            $where['status'] = $data['status'];
        }
        //总数量
        $totalSize = db($this->goodsOrderTable)->where($where)->count();
        //当前页码
        $current_page = $this->request->param('pageNum', 1);
        //分页大小
        $size = $this->request->param('size', 3);



        $list = db($this->goodsOrderTable)->where($where)->limit(($current_page - 1) * $size, $size)->order('id desc')->select();

        $activityList = db($this->goodsOrderListTable)->field('id,goods_title,goods_logo,goods_spec,create_at,order_no')->whereIn('order_no', array_unique(array_column($list, 'order_no')))->select();
        $res = [];
        foreach ($list as $key => $value){
            $res[$key]['id'] = $value['id'];
            $res[$key]['time'] = $value['create_at'];
            $res[$key]['state'] = $value['status'];
            $res[$key]['price'] = $value['price_goods'];
            $res[$key]['pay_price'] = $value['pay_price'];
            $res[$key]['order_sn'] = $value['order_no'];

            foreach ($activityList as $activity) if ($activity['order_no'] === $value['order_no']) {
                $res[$key]['activityInfo'] = $activity;
                $res[$key]['image'] = $activity['goods_logo'];
                $res[$key]['title'] = $activity['goods_title'];
                $res[$key]['start_time'] = $activity['create_at'];
                $res[$key]['goods_spec'] = $activity['goods_spec'];
            }

        }
        $resData['list'] = $res;
//        $resData['page']['totalSize'] = $totalSize;
        $resData['page']['pageSize'] = ceil($totalSize / $size);
        $this->success('订单获取成功！', $resData);
    }
}